package novel.mzx.com.fragment;

import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.bumptech.glide.Glide;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import novel.mzx.com.R;
import novel.mzx.com.activity.EditUserActivity;
import novel.mzx.com.activity.LoginActivity;
import novel.mzx.com.activity.MyClassInfoActivity;
import novel.mzx.com.activity.SearchActivity;
import novel.mzx.com.base.BaseFragment;

import novel.mzx.com.bean.CodeBean;
import novel.mzx.com.bean.SuccessBean;
import novel.mzx.com.http.Api;
import novel.mzx.com.http.SpDataUtils;
import novel.mzx.com.utils.JSONUtils;
import novel.mzx.com.utils.PermissionsUtil;
import novel.mzx.com.utils.SPUtil;

import static android.app.Activity.RESULT_OK;

/**
 * 个人中心
 */

public class MeFragment extends BaseFragment implements View.OnClickListener, PermissionsUtil.IPermissionsCallback {

    @BindView(R.id.rv_user_data)
    RelativeLayout rv_user_data;
    @BindView(R.id.rl_edit)
    RelativeLayout rl_edit;

    @BindView(R.id.rl_logout)
    RelativeLayout ll_out;
    @BindView(R.id.rl_01)
    RelativeLayout rl_01;
    @BindView(R.id.rl_02)
    RelativeLayout rl_02;




    @BindView(R.id.tv_zhuan_ye)
    TextView tv_zhuan_ye;

    @BindView(R.id.tv_user_name)
    TextView tv_user_name;


    @BindView(R.id.iv_user_head)
    ImageView iv_user_head;


    private static final int UP_Header = 55;

    private PermissionsUtil permissionsUtil;

    @Override
    public int getLayoutResID() {

        return R.layout.fragment_my;
    }

    @Override
    public void initView(View view) {
        super.initView(view);

        iv_user_head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                permissionsUtil=  PermissionsUtil
                        .with(MeFragment.this)
                        .requestCode(1)
                        .isDebug(true)//开启log
                        .permissions(PermissionsUtil.Permission.Camera.CAMERA,PermissionsUtil.Permission.Storage.READ_EXTERNAL_STORAGE,PermissionsUtil.Permission.Storage.WRITE_EXTERNAL_STORAGE)
                        .request();
            }
        });

        getUserData();
    }

    @Override
    public void initListener() {
        super.initListener();
        ll_out.setOnClickListener(this);
        rl_edit.setOnClickListener(this);
        rl_01.setOnClickListener(this);
        rl_02.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){

            case R.id.rl_edit:
                Intent ll_location = new Intent(getActivity(), EditUserActivity.class);
                startActivity(ll_location);
                break;
            case R.id.rl_01:
                Intent rl_01 = new Intent(getActivity(), MyClassInfoActivity.class);
                startActivity(rl_01);
                break;
            case R.id.rl_02:
                Intent rl_02 = new Intent(getActivity(), SearchActivity.class);
                startActivity(rl_02);
                break;
            case R.id.rl_logout:
                SPUtil.getInstance().putString("username","");
                Intent intent1 = new Intent(getActivity(),LoginActivity.class);
                startActivity(intent1);
                getActivity().finish();
                break;

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        //需要调用onRequestPermissionsResult
        permissionsUtil.onRequestPermissionsResult(requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


    @Override
    public void onPermissionsGranted(int requestCode, String... permission) {

        selectImg();
    }


    @Override
    public void onPermissionsDenied(int requestCode, String... permission) {

    }

    private void selectImg() {
        Matisse.from(this)
                .choose(MimeType.ofImage())//图片类型
                .countable(true)//true:选中后显示数字;false:选中后显示对号
                .maxSelectable(1)//可选的最大数
                .capture(true)//选择照片时，是否显示拍照
                .captureStrategy(new CaptureStrategy(true, "novel.mzx.com.fileprovider"))//参数1 true表示拍照存储在共有目录，false表示存储在私有目录；参数2与 AndroidManifest中authorities值相同，用于适配7.0系统 必须设置
                .imageEngine(new GlideEngine())//图片加载引擎
                .forResult(UP_Header);//
    }

    private List<String> path;
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        permissionsUtil.onActivityResult(requestCode, resultCode, data);
        if (requestCode == UP_Header&& resultCode == RESULT_OK) {
            List<Uri> uris = Matisse.obtainResult(data);
            path = Matisse.obtainPathResult(data);

            upImg(path.get(0));//"data:image/png;base64,"
        }
    }

    private void upImg(String s) {
        Log.e("path",s);
        OkGo.<String>post(Api.mainHost+Api.photoUploadUrl)
                .tag(this)
                .isMultipart(true)
                .params( "file",new File(s))
                .execute(new StringCallback(){
                    @Override
                    public void onSuccess(Response<String> response) {
                        Log.e("tag",response.body());

                        SuccessBean getServiceImgBean = JSONUtils.parserObject(response.body(),SuccessBean.class);
                        if (getServiceImgBean.getResultCode() == 200){
                            gettImgUrl(getServiceImgBean.getData());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);

                    }
                });
    }

    private void gettImgUrl(String data) {

        String memberId = SPUtil.getInstance().getString("memberId", "");
        OkGo.<String>post(Api.mainHost+Api.updateUserUrl)
                .params("userImg",data)
                .params("userId",memberId)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Log.e("修改头像成功",response.body());

                        getUserData();
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);

                    }
                });
    }

    private void getUserData() {
        String account = SPUtil.getInstance().getString("account");
        String pwd = SPUtil.getInstance().getString("pwd");
        OkGo.<String>get(Api.mainHost+Api.loginUrl)
                .params("userAccount",account)
                .params("demoUserPwd",pwd)
                .params("demoUserRole", SpDataUtils.getRole())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Log.e("login",response.body());

                        CodeBean codeBean = JSONUtils.parserObject(response.body(),CodeBean.class);
                        int code = codeBean.getResultCode();
                        if(code == 200){

                            String userImg = codeBean.getData().getUserImg();
                            Glide.with(getActivity()).load(Api.mainImgHost+userImg).asBitmap().placeholder(R.mipmap.icon_defoat).into(iv_user_head);
                            tv_user_name.setText(codeBean.getData().getUserName());
                        }else {

                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);

                    }
                });
    }

}
